/*
 *
 *  *    Copyright 2020-2021 Luter.me
 *  *
 *  *    Licensed under the Apache License, Version 2.0 (the "License");
 *  *    you may not use this file except in compliance with the License.
 *  *    You may obtain a copy of the License at
 *  *
 *  *      http://www.apache.org/licenses/LICENSE-2.0
 *  *
 *  *    Unless required by applicable law or agreed to in writing, software
 *  *    distributed under the License is distributed on an "AS IS" BASIS,
 *  *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  *    See the License for the specific language governing permissions and
 *  *    limitations under the License.
 *
 */

package com.luter.heimdall.plugins.redis.listener;

import com.luter.heimdall.core.config.ConfigManager;
import com.luter.heimdall.core.token.store.TokenStore;
import com.luter.heimdall.core.utils.StrUtils;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;

import static org.slf4j.LoggerFactory.getLogger;

/**
 * 监听token过期事件__keyevent@数据库__:expired"
 * <p>
 *
 * @author Luter
 */
public class RedisTokenKeyExpirationListener extends RedisKeyExpiredEventMessageListener {
    private static final transient Logger log = getLogger(RedisTokenKeyExpirationListener.class);
    /**
     * The User cache redis.
     */
    @Autowired
    private TokenStore tokenStore;

    /**
     * Instantiates a new Token redis key expiration listener.
     *
     * @param listenerContainer the listener container
     */
    public RedisTokenKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    /**
     * 针对 redis 数据失效事件，进行数据处理
     */
    @Override
    public void onMessage(Message message, byte[] pattern) {
        log.debug("[onMessage]::Token expired event,  key = [{}]", message.toString());
        String expiredKey = message.toString();
        if (StrUtils.isNotBlank(expiredKey) && expiredKey.startsWith(ConfigManager.getConfig().getToken().getCachePrefix())) {
            //去掉前缀
            String tokenId = expiredKey.replace(ConfigManager.getConfig().getToken().getCachePrefix(), "");
            log.warn("[onMessage]:: Expired Token, TokenId = [{}]", tokenId);
        } else {
            log.debug("Token expired event,key = [{}]", expiredKey);
        }

    }
}